<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\controller;

use plugin\ai\app\model\AiMessage;
use plugin\ai\app\model\AiUser;
use plugin\ai\app\service\Common;
use plugin\ai\app\service\Setting;
use plugin\ai\app\service\User;
use plugin\user\api\Limit;
use support\Db;
use support\exception\BusinessException;
use support\Response;
use Throwable;

class Base
{

    /**
     * 尝试减少余额
     * @param $model
     * @param bool $useBalance
     * @return string|null
     * @throws BusinessException
     */
    protected static function tryReduceBalance($model, bool &$useUserBalance = false): ?string
    {
        if (!$model) {
            return 'model不能为空';
        }
        $modelType = Common::getModelType($model);
        $request = request();
        $session = $request->session();
        $loginUser = $session->get('user');
        $loginUserId = $loginUser['uid'] ?? $loginUser['id'] ?? null;
        $expired = false;
        $isVip = $loginUserId && User::isVip($loginUserId, $expired);

        if (!$loginUserId && Setting::getSetting('need_login')) {
            return '[请登录](/app/ai/user/login)，游客模式下不支持该功能。';
        }
        // 尝试从余额中扣除
        if ($loginUserId && User::reduceBalance($loginUserId, $modelType)) {
            $useUserBalance = true;
            // 消息加1
            AiUser::where('user_id', $loginUserId)->update([
                'message_count' => Db::raw('message_count + 1'),
            ]);
            return null;
        }

        // 余额不足则使用每日赠送余额
        $freeCountPerDay = Common::getDayFreeCount($model);
        try {
            if (!$freeCountPerDay) {
                throw new BusinessException('余额不足');
            }
            Limit::perDay($session->getId() . "-ai-$modelType-", $freeCountPerDay);
            $ip = request()->getRealIp();
            // 非内网ip时
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                Limit::perDay("$ip-ai-$modelType-", $freeCountPerDay);
            }
            // 消息加1
            if ($loginUserId) {
                AiUser::where('user_id', $loginUserId)->update([
                    'message_count' => Db::raw('message_count + 1'),
                ]);
            }
            // 赠送余额不足则给出提示
        } catch (Throwable $e) {
            if (Setting::getSetting()['enable_payment'] ?? false) {
                if ($isVip) {
                    return "您的账户{$model}额度不足，如需继续使用请 [续费](/app/ai/user/vip?redirect=" . urlencode('/app/ai') . ")";
                }
                return "您今天{$model}消息已经达到上限，如需继续使用请 [升级会员](/app/ai/user/vip?redirect=" . urlencode('/app/ai') . ")";
            } else {
                return "您今天{$model}消息已经达到上限，如需继续使用请联系管理员。";
            }
        }

        return null;
    }

    /**
     * 保存消息
     * @param $userId
     * @param $sessionId
     * @param $messageId
     * @param $roleId
     * @param $role
     * @param $content
     * @param $remoteIp
     * @param $model
     * @param $chatId
     * @return void
     */
    protected function saveMessage($userId, $sessionId, $messageId, $roleId, $role, $content, $remoteIp, $model, $chatId = null)
    {
        $content = is_array($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content;
        $aiMessage = new AiMessage();
        $aiMessage->user_id = $userId;
        $aiMessage->session_id = $sessionId;
        $aiMessage->message_id = $messageId;
        $aiMessage->role_id = $roleId;
        $aiMessage->role = $role;
        $aiMessage->content = $content;
        $aiMessage->ip = $remoteIp;
        $aiMessage->model = $model;
        $aiMessage->chat_id = $chatId;
        $aiMessage->save();
    }

    /**
     * AI是否开启了支付宝支付
     *
     * @return bool
     */
    public static function alipayEnabled(): bool
    {
        static $enabled;
        if ($enabled === null) {
            $enabled = config('plugin.ai.payment.alipay.default.alipay_root_cert_path');
        }
        return (bool)$enabled;
    }

    /**
     * AI是否开启了微信支付
     *
     * @return bool
     */
    public static function wechatEnabled(): bool
    {
        static $enabled;
        if ($enabled === null) {
            $enabled = config('plugin.ai.payment.wechat.default.mch_public_cert_path');
        }
        return (bool)$enabled;
    }


    /**
     * AI是否开启了支付
     *
     * @return bool
     */
    public static function payEnabled(): bool
    {
        static $enabled;
        if ($enabled === null) {
            $enabled = static::wechatEnabled() || static::alipayEnabled();
        }
        return (bool)$enabled;
    }

    /**
     * @param $code
     * @param string $msg
     * @param mixed $data
     * @return Response
     */
    protected function json($code, string $msg = 'ok', $data = []): Response
    {
        return json(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }

}
